<template>
	<view>
		<u-popup :show="show" :round="10" closeable mode="bottom" @close="close">
			<view class="choose-dish">
				<view class="dish-card">
					<view>
						<image style="width: 150upx;height: 150upx;" mode="aspectFit" :src="dish.image"></image>
					</view>
					<view>
						<view>{{dish.dishName}}</view>
						<view>{{getSpe()}}</view>
						<view>预估价格</view>
						<view>{{dish.price}}</view>
					</view>
				</view>
				<view class="dish-num">
					<view>数量</view>
					<view><u-number-box v-model="dish_num"></u-number-box></view>
				</view>
				<!-- 规格选择列表 -->
				<view>
					<view v-for="item in dish.specifications" :key="item.id">
						<view>{{item.specificationName}}</view>
						<view class="specification-item">
							<view v-for="(spe,index) in JSON.parse(item.dataList)" :key="index"
								@click="select(item.id,spe)"
								:class="{'specification-select':currentSpe[item.id] == spe}">
								{{spe}}
							</view>
						</view>
					</view>
				</view>
				<u-button text="添加到购物车" type="primary" @click="add_to_cart"></u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {add_cart} from '@/api/cart.js'
	export default {
		name: "choose-dish",
		props: {
			show: {
				type: Boolean,
				default: false
			},
			dish: {
				type: Object,
				default: () => {}
			}
		},
		data() {
			return {
				currentSpe: {},
				dish_num: 1
			}
		},
		methods: {
			close() {
				this.$emit("close")
			},
			select(id, spe) {
				this.currentSpe[id] = spe
				this.$forceUpdate()
			},
			getSpe(){
				const result = []
				for (let item in this.currentSpe) {
					result.push(this.currentSpe[item])
				}
				return result.length>0?result.join("/"):"未选择"
			},
			add_to_cart() {
				const specification = []
				for (let item in this.currentSpe) {
					specification.push({
						id: item,
						value: this.currentSpe[item]
					})
				}
				const data = {
					dishId: this.dish.id,
					shopId:this.dish.shopId,
					quantity: this.dish_num,
					specification: JSON.stringify(specification)
				}
				console.log(data)
				add_cart(data).then(res=>{
					uni.showToast({
						icon:"success",
						title:"添加成功"
					})
				})
				this.$emit("add_to_cart")
			}
		}
	}
</script>

<style scoped>
	.choose-dish>view {
		width: 96%;
		margin: 10upx auto;
	}

	.dish-card {
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		align-items: flex-start;
		background-color: #eee;
	}

	.dish-num {
		display: flex;
		justify-content: space-between;
		flex-direction: row;
	}

	.specification-item {
		display: grid;
		grid-template-columns: repeat(3, 32%);
		grid-column-gap: 2px;
		grid-row-gap: 5px;
		justify-content: space-between;
	}

	.specification-select {
		background-color: #ebf9ff !important;
		border: 2upx solid #02b6fd;
	}

	.specification-item>view {
		height: 80upx;
		line-height: 80upx;
		text-align: center;
		border-radius: 10upx;
		background-color: #f5f5f5;
	}
</style>